﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HotShot.Entities;

namespace HotShot.Service.BusinessLogic.MessageProcessors
{
    public class RetrieveBroadcastProcessor : MessageProcessorBase
    {
        public override void ProcessMessage(HotShot.Entities.Messages.BaseMessage message, string correlationId)
        {
            var entity = message.XmlPayload.FromXml<StorageEntity>();
            var nodes = ClusterProcessorLogic.Current.GetNodesForEntityKey(entity.Key, MessagingLogic.Current.RetrieveTotal);

            int i = 0;
            Trace.WriteLine(String.Format("Forwarding retrieve message to {0} of {1} nodes", nodes.Count, MessagingLogic.Current.RetrieveTotal));
            MessageCorrelationLogic.Current.SetupCorrelation(correlationId, nodes);

            foreach (var node in nodes)
            {
                message.ReturnAddress = ClusterProcessorLogic.Current.ProcessorId;
                entity.StoreCount = MessagingLogic.Current.RetrieveTotal;
                entity.StoreIndex = i;
                i++;
                message.XmlPayload = entity.ToXml();
                QueueCommunicationLogic.Current.SendInputMessage(node.NodeId, message, correlationId);
            }
        }
    }
}
